package com.maikec.utils.jwt;
/**
 * 邢帅教育
 * <p>
 * 本源代码由数据中心及其作者共同所有，未经版权持有者的事先书面授权，
 * 不得使用、复制、修改、合并、发布、分发和/或销售本源代码的副本。
 *
 * @copyright Copyright (c) 2018. [图片]xsteach.com all rights reserved.
 */

import com.maikec.configure.JwtConfig;
import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.DefaultClaims;
import io.jsonwebtoken.impl.compression.GzipCompressionCodec;

import java.util.Calendar;

/**
 * jwt token生成器
 * @author maikec
 * @date 2018/7/24
 */
public class JwtFactory {
    private static JwtFactory jwtFactory;
    public static JwtFactory getInstance(){
        if (null == jwtFactory) {
            synchronized(JwtFactory.class){
                return new JwtFactory();
            }
        } else {
            return jwtFactory;
        }
    }

    /**
     * 生成token
     * @param userId
     * @return
     */
    public String generateToken(String userId) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.MINUTE, JwtConfig.getExpiration());
        Claims claims = new DefaultClaims();
        claims.setId(userId);
        claims.setSubject(JwtConfig.getSubject())
                .setExpiration(calendar.getTime())
                .setIssuer(JwtConfig.getIssuer());

        return Jwts.builder().
                addClaims(claims).compressWith(new GzipCompressionCodec())
                .signWith(SignatureAlgorithm.HS512, JwtConfig.getSecretKey()).compact();
    }

    public void checkToken(String jwt) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException{
        Jwts.parser().setSigningKey(JwtConfig.getSecretKey()).parseClaimsJws(jwt).getBody();
    }
}
